package com.smart.common.scheduler.service;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import com.google.common.collect.Lists;
import com.smart.common.PlatformConfig;
import com.smart.common.enums.ConstructionStatusEnum;
import com.smart.common.enums.SmsTemplateEnum;
import com.smart.mapper.HotWorkMapper;
import com.smart.mapper.ManageUserRegistrationMapper;
import com.smart.mapper.ProjectChangeReviewMapper;
import com.smart.mapper.ProjectMapper;
import com.smart.mapper.ProjectReportMapper;
import com.smart.mapper.ProjectWeeklyTaskMapper;
import com.smart.model.domain.ProjectDO;
import com.smart.model.domain.ProjectWeeklyTaskDO;
import com.smart.utils.SmsUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @author: zyh
 * @date: 2023-09-25
 */
@Slf4j
@Component
public class UserAndProjectManagementScheduleService {
    @Autowired
    private ProjectMapper projectMapper;
    @Autowired
    private ProjectChangeReviewMapper projectChangeReviewMapper;
    @Autowired
    private ManageUserRegistrationMapper userRegistrationMapper;
    @Autowired
    private HotWorkMapper hotWorkMapper;
    @Autowired
    private ProjectWeeklyTaskMapper projectWeeklyTaskMapper;
    @Autowired
    private ProjectReportMapper projectReportMapper;
    @Autowired
    private PlatformConfig platformConfig;
    @Autowired
    private ManageUserRegistrationMapper manageUserRegistrationMapper;

    public void userWarn() {
        LocalDate localDate = LocalDate.now();
        // 获取上周一的日期
        LocalDate monday = localDate.with(TemporalAdjusters.previous(DayOfWeek.MONDAY));
        // 获取上周日的日期
        LocalDate friday = localDate.with(TemporalAdjusters.previousOrSame(DayOfWeek.SUNDAY));
        Date startTime = Date.from(monday.atStartOfDay(ZoneId.systemDefault()).toInstant());
        Date time = Date.from(friday.atStartOfDay(ZoneId.systemDefault()).toInstant());
        Date endTime = DateUtil.parse(DateUtil.format(time, DatePattern.NORM_DATE_PATTERN) + " 23:59:59", DatePattern.NORM_DATETIME_PATTERN);
        List<ProjectDO> projectDOList = projectMapper.selectProjectByTime(startTime);
        projectDOList.forEach(item -> {
            Long projectId = item.getId();
            Integer count = projectChangeReviewMapper.selectByParames(projectId, startTime, endTime);
            if (count < 1) {
                //查询项目上周有无人员进离场
                Integer userCount = userRegistrationMapper.selectByParames(projectId, startTime, endTime);
                if (userCount < 1) {
                    List<String> list = userRegistrationMapper.selectCountPerson(projectId);
                    String personCount = "0";
                    if (CollectionUtils.isNotEmpty(list)) {
                        personCount = Integer.valueOf(list.size()).toString();
                    }
                    String shigongContactPhone = item.getShigongContactPhone();
                    List<String> phones = new ArrayList<>();
                    phones.add(shigongContactPhone);
                    LinkedHashMap<String, String> dataMap = new LinkedHashMap<>();
                    dataMap.put("number", personCount);
                    SmsUtil.sendMessage(phones, SmsTemplateEnum.SMS_463146266, dataMap);
                }
            }
        });
    }

    public void projectStatistics() {
        LocalDate localDate = LocalDate.now();
        //周一
        LocalDate monday = localDate.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
        Date startTime = Date.from(monday.atStartOfDay(ZoneId.systemDefault()).toInstant());
        Date endTime = new Date();
        List<ProjectDO> projectDOList = projectMapper.selectProjectByParames();
        projectDOList.forEach(item -> {
            Long projectId = item.getId();
            //在场人数
            String notLeave = "0";
            //进场人数
            String inCount = "0";
            //离场人数
            String outCount = "0";
            //提交动火作业次数
            String hotworkCount = "0";
            List<String> list = userRegistrationMapper.selectCountPerson(projectId);
            if (CollectionUtils.isNotEmpty(list)) {
                notLeave = Integer.valueOf(list.size()).toString();
            }
            Integer in = userRegistrationMapper.selectByParames(projectId, startTime, endTime);
            Integer out = userRegistrationMapper.selectOutCountByTime(startTime, endTime, projectId);
            Integer hotwork = hotWorkMapper.selectCountByParams(projectId, startTime, endTime);
            inCount = in.toString();
            outCount = out.toString();
            hotworkCount = hotwork.toString();
            LinkedHashMap<String, String> dataMap = new LinkedHashMap<>();
            dataMap.put("number1", notLeave);
            dataMap.put("number2", inCount);
            dataMap.put("number3", outCount);
            dataMap.put("number4", hotworkCount);
            List<String> phones = new ArrayList<>();
            phones.add(item.getShigongHeadPhone());
            phones.add(item.getShigongContactPhone());
            //SmsUtil.sendMessage(phones, SmsTemplateEnum.SMS_463136378, dataMap);
        });
    }

    /**
     * 一周平台数据统计
     */
    public void platformStatistics() {
        BigDecimal c = new BigDecimal(100);
        LocalDate localDate = LocalDate.now();
        // 获取上周一的日期
        //LocalDate lastMonday = localDate.with(TemporalAdjusters.previous(DayOfWeek.MONDAY));
        // 获取上周日的日期
        //LocalDate lastSunday = localDate.with(TemporalAdjusters.previousOrSame(DayOfWeek.SUNDAY));
        //Date startTime = Date.from(lastMonday.atStartOfDay(ZoneId.systemDefault()).toInstant());
        //Date endTimeTemp = Date.from(lastSunday.atStartOfDay(ZoneId.systemDefault()).toInstant());
        //Date endTime = DateUtil.parse(DateUtil.format(endTimeTemp, DatePattern.NORM_DATE_PATTERN) + " 23:59:59", DatePattern.NORM_DATETIME_PATTERN);
        //String[] s = lastMonday.toString().split("-");
        //String[] e = lastSunday.toString().split("-");
        //上周时间
        //String time = s[0] + "年" + s[1] + "月" + s[2] + "日" + "-" + e[0] + "年" + e[1] + "月" + e[2] + "日";
        DateTime lastMonday = DateUtil.beginOfWeek(DateUtil.lastWeek().toJdkDate());
        Date startTime = DateUtil.parse(DateUtil.format(lastMonday, DatePattern.NORM_DATETIME_PATTERN)).toJdkDate();
        DateTime lastSunday = DateUtil.endOfWeek(DateUtil.lastWeek().toJdkDate());
        Date endTime = DateUtil.parse(DateUtil.format(lastSunday, DatePattern.NORM_DATETIME_PATTERN)).toJdkDate();
        String time = DateUtil.format(lastMonday, DatePattern.CHINESE_DATE_PATTERN) + "-" + DateUtil.format(lastSunday, DatePattern.CHINESE_DATE_PATTERN);
        //在监工程
        Integer startProject = projectMapper.countOnlineProject();
        //在施项目
        String runningCount = "0";
        //在施项目占比
        String runningPercent = "0";
        //新注册项目
        String newProject = "0";
        List<ProjectDO> projectList = projectMapper.selectBuildStatus();
        Integer newProjectCount = projectMapper.selectNewProjectByTime(startTime, endTime);
        newProject = newProjectCount.toString();
        if (CollectionUtils.isNotEmpty(projectList)) {
            List<ProjectDO> runningProject = projectList.stream()
                    .filter(item -> ConstructionStatusEnum.RUNNING.getCode().equals(item.getConstructionStatus()))
                    .collect(Collectors.toList());
            runningCount = Integer.valueOf(runningProject.size()).toString();
            BigDecimal a = new BigDecimal(runningProject.size());
            BigDecimal b = new BigDecimal(projectList.size());
            if (!BigDecimal.ZERO.equals(b)) {
                runningPercent = a.divide(b, 3, RoundingMode.HALF_UP).multiply(c).setScale(1, RoundingMode.HALF_UP).toPlainString();
                String[] split = runningPercent.split("\\.");
                if ("0".equals(split[1])) {
                    runningPercent = split[0];
                }
            }
        }

        //在监项目人员
        Integer personCount = manageUserRegistrationMapper.countOnlineProjectPersonCount();
        //有进离场的项目数
        String leaveOrNotCount = "0";
        //人员占比
        String personPercent = "0";
        //进场人次
        String inCount = "0";
        //离场人次
        String outCount = "0";
        //提交动火作业的项目数
        String projectCount = "0";
        //未提交动火作业的在施项目数
        String runningHotworkCount = "0";
        //提交动火作业项目在在施项目中的占比
        String runHotpercent = "0";
        //项目数环比(增加/减少了XX个/持平)
        String projectChainRatio = "持平";
        //动火作业数
        String hotworkCount = "0";
        //动火作业数(环比增加/减少了XX.X%/持平)
        String hotworkChainRatio = "持平";

        HashSet<String> personSet = new HashSet<>();
        AtomicInteger leaveOrNot = new AtomicInteger(0);
        AtomicInteger notLeave = new AtomicInteger(0);
        AtomicInteger leave = new AtomicInteger(0);

        //查询全区截止当前时间点所有在场人数
        if (CollectionUtils.isNotEmpty(projectList)) {
            projectList.forEach(item -> {
                Long projectId = item.getId();
                List<String> idCards = userRegistrationMapper.selectPersonIdCards(projectId);
                personSet.addAll(idCards);
                //Integer in = userRegistrationMapper.selectByParames(projectId, startTime, endTime);
                Integer in = manageUserRegistrationMapper.countPersonNum(projectId, startTime, endTime, 1);
                if (in > 0) {
                    notLeave.addAndGet(in);
                }
                //Integer out = userRegistrationMapper.selectOutCountByTime(startTime, endTime, projectId);
                Integer out = manageUserRegistrationMapper.countPersonNum(projectId, startTime, endTime, 0);
                if (out > 0) {
                    leave.addAndGet(out);
                }
                if (in>0 || out>0){
                    leaveOrNot.addAndGet(1);
                }
            });
        }
        leaveOrNotCount = Integer.valueOf(leaveOrNot.get()).toString();
        inCount = Integer.valueOf(notLeave.get()).toString();
        outCount = Integer.valueOf(leave.get()).toString();
        if (projectList.size() > 0) {
            BigDecimal a = new BigDecimal(leaveOrNot.get());
            BigDecimal b = new BigDecimal(projectList.size());
            personPercent = a.divide(b, 3, RoundingMode.HALF_UP).multiply(c).setScale(1, RoundingMode.HALF_UP).toPlainString();
            String[] split = personPercent.split("\\.");
            if ("0".equals(split[1])) {
                personPercent = split[0];
            }
        }
        List<Long> hotworks = hotWorkMapper.selectProjectCountByParams(startTime, endTime);
        HashSet<Long> hotworkSet = new HashSet<>();
        hotworkSet.addAll(hotworks);
        projectCount = Integer.valueOf(hotworkSet.size()).toString();
        //全区在施项目
        List<Long> runningProject = projectMapper.selectRunningProjectCount();
        AtomicInteger notUploadProject = new AtomicInteger(0);
        if (CollectionUtils.isNotEmpty(runningProject)) {
            runningProject.forEach(item -> {
                Integer integer = hotWorkMapper.selectCountByParams(item, startTime, endTime);
                if (integer < 1) {
                    notUploadProject.addAndGet(1);
                }
            });
        }
        runningHotworkCount = Integer.valueOf(notUploadProject.get()).toString();
        //已提交动火作业的在施项目
        Integer a = runningProject.size() - notUploadProject.get();
        BigDecimal b = new BigDecimal(a);
        BigDecimal d = new BigDecimal(runningProject.size());
        if (!BigDecimal.ZERO.equals(d)) {
            runHotpercent = b.divide(d, 3, RoundingMode.HALF_UP).multiply(c).setScale(1, RoundingMode.HALF_UP).toPlainString();
            String[] split = runHotpercent.split("\\.");
            if ("0".equals(split[1])) {
                runHotpercent = split[0];
            }
        }
        LocalDate twoWeeksAgo = localDate.minusWeeks(2); // 往前推两周

        // 上上周的周一
        Date startDate = Date.from(twoWeeksAgo.with(DayOfWeek.MONDAY).atStartOfDay(ZoneId.systemDefault()).toInstant());
        // 上上周的周天
        Date endDate = Date.from(twoWeeksAgo.with(DayOfWeek.SUNDAY).atStartOfDay(ZoneId.systemDefault()).toInstant());
        endDate = DateUtil.parse(DateUtil.format(endDate, DatePattern.NORM_DATE_PATTERN) + " 23:59:59", DatePattern.NORM_DATETIME_PATTERN);
        List<Long> hotworkOlds = hotWorkMapper.selectProjectCountByParams(startDate, endDate);
        HashSet<Long> hotworkOldSet = new HashSet<>();
        hotworkOldSet.addAll(hotworkOlds);
        int oldSize = hotworkOldSet.size();
        int newSize = hotworkSet.size();
        if (newSize > oldSize) {
            Integer size = newSize - oldSize;
            projectChainRatio = "增加" + size + "个";
        } else if (newSize < oldSize) {
            Integer size = oldSize - newSize;
            projectChainRatio = "减少" + size + "个";
        }
        hotworkCount = Integer.valueOf(hotworks.size()).toString();
        int sizeOne = hotworks.size();//上周
        int sizeTwo = hotworkOlds.size();//上上周
        if (sizeOne > sizeTwo) {
            BigDecimal size = new BigDecimal(sizeOne - sizeTwo);
            BigDecimal decimal = new BigDecimal(sizeTwo);
            if (BigDecimal.ZERO.equals(decimal)) {
                hotworkChainRatio = "增加了100%";
            } else {
                String plainString = size.divide(decimal, 3, RoundingMode.HALF_UP).multiply(c).setScale(1, RoundingMode.HALF_UP).toPlainString();
                String[] split = plainString.split("\\.");
                if ("0".equals(split[1])) {
                    plainString = split[0];
                }
                hotworkChainRatio = "增加了" + plainString + "%";
            }
        } else if (sizeOne < sizeTwo) {
            BigDecimal size = new BigDecimal(sizeTwo - sizeOne);
            BigDecimal decimal = new BigDecimal(sizeTwo);
            if (BigDecimal.ZERO.equals(decimal)) {
                hotworkChainRatio = "持平";
            } else {
                String plainString = size.divide(decimal, 3, RoundingMode.HALF_UP).multiply(c).setScale(1, RoundingMode.HALF_UP).toPlainString();
                String[] split = plainString.split("\\.");
                if ("0".equals(split[1])) {
                    plainString = split[0];
                }
                hotworkChainRatio = "减少了" + plainString + "%";
            }
        }
        //数据提报相关-start
        //提交周报项目数【已提交】
        String weeklyCount = "0";
        //应提交周报项目个数【应提交】
        String mustWeeklyCount = "0";
        //提交项目占比
        String weeklyReportPercent = "0";
        ProjectWeeklyTaskDO weeklyTask = projectWeeklyTaskMapper.getByStartAndEndTime(startTime, endTime);
        if (weeklyTask != null) {
            //weeklyCount = projectReportMapper.weeklyCount(weeklyTask.getId());
            //mustWeeklyCount = projectReportMapper.mustWeeklyCount(weeklyTask.getId());

            Long reportNum = projectReportMapper.reportCountRangeProject(weeklyTask.getId(), null);
            Long unReportNum = projectReportMapper.unReportCountRangeProject(weeklyTask.getId(), null);
            weeklyCount = Optional.ofNullable(reportNum).map(String::valueOf).orElse(null);
            mustWeeklyCount = reportNum + unReportNum + "";
            if (weeklyCount != null) {
                weeklyReportPercent = div(weeklyCount, mustWeeklyCount);
            }
        }
        //数据提报相关-end

        // 读取配置的手机号，禁止在代码这里硬编码，防止发布后影响到线上
        List<String> phones = platformConfig.getPhones();

        LinkedHashMap<String, String> dataMap = new LinkedHashMap<>();
        dataMap.put("time", time);
        dataMap.put("num1", String.valueOf(startProject));
        dataMap.put("num2", runningCount);
        dataMap.put("num3", runningPercent);
        dataMap.put("num4", newProject);
        dataMap.put("num5", String.valueOf(personCount));

        dataMap.put("num6", leaveOrNotCount);//一周内有人员进出场的项目数量
        dataMap.put("num7", personPercent);//占比
        dataMap.put("num8", inCount);//进场人次
        dataMap.put("num9", outCount);//离场人次

        //dataMap.put("num10", projectCount);
        //dataMap.put("num11", runningHotworkCount);
        //dataMap.put("num12", runHotpercent);
        //dataMap.put("num13", projectChainRatio);
        //dataMap.put("num14", hotworkCount);
        //dataMap.put("num15", hotworkChainRatio);
        dataMap.put("num16", weeklyCount);
        dataMap.put("num17", mustWeeklyCount);
        dataMap.put("num18", weeklyReportPercent);
        //SmsUtil.sendMessage(phones, SmsTemplateEnum.SMS_463290014, dataMap);
        SmsUtil.sendMessage(phones, SmsTemplateEnum.SMS_464541130, dataMap);
    }

    /**
     * 计算百分比
     * @param a
     * @param b
     * @return
     */
    private String div(String a, String b) {
        String div = NumberUtil.div(a, b, 3) + "";
        String mul = NumberUtil.mul(div, "100").setScale(1) + "";
        String[] split = mul.split("\\.");
        if ("0".equals(split[1])) {
            return split[0];
        }
        return mul;
    }
}
